package com.yubest.security.filter;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.yubest.security.bean.Response;
import com.yubest.security.bean.UserInfo;
import com.yubest.security.service.TokenService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyLogoutHandler implements LogoutHandler {

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        TokenService tokenService = SpringUtil.getBean(TokenService.class);
        UserInfo userInfo = tokenService.getCurrentUser();
        if (null != userInfo) {
            tokenService.remove(userInfo.getToken());
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        Response<String> data = Response.ok("退出成功");
        ServletUtil.write(httpServletResponse, JSONUtil.toJsonStr(data), "application/json;charset=utf-8");
    }
}
